package com.bite.gateway.filter;

import com.bite.common.pojo.Result;
import com.bite.common.utils.JWTUtils;
import com.bite.gateway.properties.AuthWhiteName;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthWhiteName authWhiteName;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //白名单
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (match(path, authWhiteName.getUrl())) {
            //白名单直接放行
            return chain.filter(exchange);
        }
        String userToken = request.getHeaders().getFirst("user_token");
        if (!StringUtils.hasLength(userToken)) {
           //无令牌
            return unauthorizedResponse(exchange, "令牌不能为空！");
        }
        if (JWTUtils.parseJWT(userToken) == null) {
            //令牌校验失败
            return unauthorizedResponse(exchange, "令牌过期或不合法！");
        }
        return chain.filter(exchange);
    }

    private boolean match(String path, List<String> url) {
        if(url == null || url.size() == 0) {
            return false;
        }
        return url.contains(path);
    }

    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String errMsg) {
        log.info("[用户认证失败], url: {}", exchange.getRequest().getURI().getPath());
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //添加Header，设置类型
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        //创建要返回的错误结果对象
        Result<Void> result = Result.fail(errMsg);
        //将结果对象序列化为JSON字节数组, 并封装成DataBuffer对象
        DataBuffer dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        //将DataBuffer包装成Mono（响应式流发布者）, 将响应数据写入客户端
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
